<?php


namespace App\Http\Controllers\Index;


use App\Http\Controllers\Controller;
use App\Model\Banner;
use App\Model\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    public function user_info(Request $request){
        JsonResponse(200,true,'获取成功',$request->header('token'));
        $user = Users::where('token',$request->header('token'))->first();
        return JsonResponse(200,true,'获取成功',$user,$request->header('token'));
    }

    public function avatar_upload(Request $request){
        $name = md5(time());
        $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        if (!is_dir("./images/user_avatar/")) {
            mkdir("./images/user_avatar/");
        }
        $path = "./images/user_avatar/" . $name . '.' . $ext;
        $move = move_uploaded_file($_FILES["file"]["tmp_name"], $path);
        if ($move){
            return JsonResponse(200,true,'上传成功',['url' => $path]);
        }else{
            return JsonResponse(3001,false,'网络错误，请稍后重试');
        }
    }

    public function edit_user(Request $request){
        $data = $request->post();
        $userId = $data['user_id'];
        unset($data['user_id']);
        $result = DB::table('users')
            ->where('id',$userId)
            ->update($data);
        if ($result){
            return JsonResponse(200,true,'修改成功') ;
        }else{
            return JsonResponse(3001,false,'网络错误，请稍后重试');
        }
    }

    public function collection(Request $request){
        $collection = DB::table('product')
            ->join('user_collection', 'product.id', '=', 'user_collection.product_id')
            ->where('user_collection.user_id',$request->get('user_id'))
            ->select('product.*')
            ->paginate(20);
        return JsonResponse(200,true,'获取成功',$collection) ;
    }
}
